import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, Select, Popconfirm, DatePicker, Modal, Input } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import { queryDictionaryList, delDictionary, saveDictionary } from '@/services/dictionary'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import TableContainer from '@/components/TableContainer';
import { DictionaryType } from '@/constants/enums/dictionary';
import { Access } from '@umijs/max';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import TableActions from '@/components/TableActions';

const DictionaryPage: React.FC = () => {
  const [searchForm] = Form.useForm<Dictionary.QueryDictionaryListParams>()
  const [searchParams, setSearchParams] = useState<Dictionary.QueryDictionaryListParams>({
    pageNum: 1, pageSize: 10,
  })
  const dictionaryList = useRequest(() => queryDictionaryList(searchParams), {
    refreshDeps: [searchParams],
  })
  const save = useRequest(saveDictionary, {manual: true})
  const [currentRecord, setCurrentRecord] = useState<Dictionary.Entity>()
  const [editModalOpen, setEditModalOpen] = useState(false)
  const [editDictionaryForm] = Form.useForm()

  const openEditModal = (record?: Dictionary.Entity) => {
    if (record) {
      editDictionaryForm.setFieldsValue({
        id: record.id,
        keyType: record.keyType,
        keyName: record.keyName,
        keyValue: record.keyValue.split(','),
      })
    } else {
      editDictionaryForm.setFieldsValue({
        id: undefined,
        keyType: undefined,
        keyName: undefined,
        keyValue: [''],
      })
    }
    setCurrentRecord(record)
    setEditModalOpen(true)
  }

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      keyType: formValues.type,
      beginTime: formValues.dateRange?.[0]?.format('YYYY-MM-DD'),
      endTime: formValues.dateRange?.[1]?.format('YYYY-MM-DD'),
      pageNum: 1,
    })
  }

  const onEditModalCancel = () => {
    setCurrentRecord(undefined)
    setEditModalOpen(false)
  }

  const onEditModalOk = () => {
    editDictionaryForm.validateFields().then((values: any) => {
      save.runAsync({
        id: values.id,
        keyType: values.keyType,
        keyName: values.keyName,
        keyValue: values.keyValue.join(','),
      }).then(() => {
        onEditModalCancel()
        dictionaryList.refresh()
      })
    })
  }

  const onEditModalValuesChange = (changeValues: any) => {
    if (changeValues.keyType) {
      editDictionaryForm.setFieldsValue({
        keyValue: ['']
      })
    }
  }

  const columns: ColumnsType<Dictionary.Entity> = [
    {
      title: '属性类型',
      dataIndex: 'keyType',
      render: keyType => keyType && DictionaryType[keyType],
    },
    {
      title: '属性名',
      dataIndex: 'keyName',
    },
    {
      title: '属性值',
      dataIndex: 'keyValue',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: createTime => dayjs(createTime).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 'max-content',
      fixed: 'right',
      render: (id: number, record) => {
        return <TableActions>
          <a onClick={() => openEditModal(record)}>修改</a>
          <Popconfirm
            title={`确定删除吗?`}
            onConfirm={() => delDictionary({infoId: record.id, status: 3}).then(dictionaryList.refresh)}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </TableActions>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      dictionaryList.refresh()
    }
    window.addEventListener('refreshDictionaryList', refresh)
    return () => {
      window.removeEventListener('refreshDictionaryList', refresh)
    }
  }, [])
  
  return (
    <TableContainer>
      <TableContainer.Toolbar>
        <Button type='primary' onClick={() => openEditModal()}>添加</Button>
      </TableContainer.Toolbar>
      <TableContainer.SearchContainer>
        <Form name='searchDictionaryForm' colon={false} form={searchForm} onFinish={onFinish}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Form.Item label='属性类型' name='type'>
                <Select placeholder='请选择' variant='borderless' options={enum2options(DictionaryType)} allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='创建时间' name='dateRange'>
                <DatePicker.RangePicker variant='borderless' style={{width: '100%'}} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Space>
                <Button type='primary' htmlType='submit' loading={dictionaryList.loading}>筛选</Button>
                <Button htmlType='reset'>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </TableContainer.SearchContainer>
      <Table<Dictionary.Entity>
        rowKey='id'
        loading={dictionaryList.loading}
        dataSource={dictionaryList.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: dictionaryList.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
      <Modal
        open={editModalOpen}
        title={currentRecord ? '修改字典' : '添加字典'}
        onOk={onEditModalOk}
        onCancel={onEditModalCancel}
        confirmLoading={save.loading}
      >
        <Form name='editDictionaryForm' form={editDictionaryForm} onValuesChange={onEditModalValuesChange}>
          <Form.Item name='id' noStyle>
            <Input hidden />
          </Form.Item>
          <Form.Item label='属性类型' name='keyType' rules={[{required: true, message: '请选择属性类型'}]}>
            <Select
              placeholder='请选择'
              options={enum2options(DictionaryType)}
              style={{width: '83.33%'}}
            />
          </Form.Item>
          <Form.Item label='属性名' name='keyName' rules={[{required: true, message: '请输入属性名'}]}>
            <Input placeholder='请输入' style={{width: '83.33%'}} />
          </Form.Item>
          <Form.Item dependencies={['keyType']}>
            {
              ({getFieldValue}) => {
                const keyType = getFieldValue('keyType')
                return <Form.List name='keyValue'>
                  {(fields, { add, remove }) => {
                    return fields.map((field, index) => (
                      <Form.Item key={field.key} label={index ? ' ' : '属性值'} required={index < 1} colon={index < 1} labelCol={{flex: '67px'}}>
                        <Row>
                          <Col span={20}>
                            <Form.Item name={field.name} noStyle rules={[{required: true, message: '请输入属性值'}]}>
                              <Input placeholder='请输入' />
                            </Form.Item>
                          </Col>
                          <Col span={4}>
                            <Access accessible={index === fields.length - 1}>
                              <Space align='center' style={{height: '100%', paddingLeft: 8}}>
                                <Access accessible={keyType === DictionaryType.列表}>
                                  <PlusCircleOutlined style={{color: 'green', cursor: 'pointer'}} onClick={() => add()} />
                                </Access>
                                <Access accessible={index > 0 && index === fields.length - 1}>
                                  <MinusCircleOutlined style={{color: 'red', cursor: 'pointer'}} onClick={() => remove(index)} />
                                </Access>
                              </Space>
                            </Access>
                          </Col>
                        </Row>
                      </Form.Item>
                    ))
                  }}
                </Form.List>
              }
            }
          </Form.Item>
        </Form>
      </Modal>
    </TableContainer>
  );
};

export default DictionaryPage;
